package com.share.shop.h5.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.share.shop.h5.model.db.User;
import com.share.shop.h5.mapper.UserMapper;
import com.share.shop.h5.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author author
 * @since 2023-03-07
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public User createOrUpdateUser(String openid, String sessionKey, String unionid) {
        //1.查询用户信息
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid", openid);
        queryWrapper.eq("status", "1");
        User user = userMapper.selectOne(queryWrapper);

        Date curDate = new Date();
        if (user == null) {
            //2.新增用户
            user = new User();
            user.setOpenid(openid);
            user.setSessionKey(sessionKey);
            user.setUnionid(unionid);
            user.setCreateTime(curDate);
            user.setUpdateTime(curDate);
            user.setStatus("1");
            userMapper.insert(user);
        } else {
            //3.更新用户信息
            User tmpUser = new User();
            tmpUser.setUpdateTime(curDate);
            tmpUser.setSessionKey(sessionKey);
            tmpUser.setUnionid(unionid);
            userMapper.updateById(tmpUser);

            //更新当前这个模型
            user.setUpdateTime(curDate);
            user.setSessionKey(sessionKey);
            user.setUnionid(unionid);
        }

        return user;
    }
}
